package zhoujunhao.rbac.service.array;

import zhoujunhao.rbac.domian.dto.DeptDto;
import zhoujunhao.rbac.domian.entity.Dept;
import zhoujunhao.rbac.domian.vo.DeptVo;
import zhoujunhao.rbac.domian.vo.Result;
import zhoujunhao.rbac.service.IDeptService;
import zhoujunhao.rbac.service.IUserService;

/**
 * 业务层-部门
 *
 * @author 周均壕
 * @since 2025/6/16 03:51
 */
public class DeptService extends BaseService<Dept, DeptDto, DeptVo> implements IDeptService {


    private static IDeptService singleton;
    private IUserService userService;

    private DeptService() {
        date = new Dept[DATA_SIZE];
        temp = new DeptVo[DATA_SIZE];
    }

    public static IDeptService getInstance() {
        if (singleton == null) {
            singleton = new DeptService();
        }
        return singleton;
    }

    @Override
    DeptVo convertToVo(Dept dept) {
        return new DeptVo(dept.getId(), dept.name, dept.phone);
    }

    @Override
    Dept createEntity(DeptDto dto, int id) {
        return new Dept(id, dto.name, dto.phone);
    }

    @Override
    void updateEntity(DeptDto dto, Dept dept) {
        dept.name = dto.name;
        dept.phone = dto.phone;
    }

    @Override
    public Result delete(int id) {
        if (!existsByid(id)) {
            return Result.failure("删除失败，不存在此数据");
        }
        if (userService == null) {
            userService = UserService.getInstance();
        }
        if (userService.deptInUse(id)) {
            return Result.failure("删除失败，还有用户属于该部门，不能删除");
        }
        date[id] = null;
        return Result.success("删除成功", null);
    }
}
